package com.wntime.simulator.device;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.wntime.simulator.common.Suffix;
import com.wntime.simulator.utils.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.iq80.leveldb.DB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import static java.nio.charset.StandardCharsets.UTF_8;

@Service
@Slf4j
public class LevelDBService {
    @Autowired
    private DB  db;
    public  List<String> getSims() throws Exception {
        byte[] bytes = db.get(Suffix.SIMS.getBytes());
        if (bytes != null) {
            String s = new String(bytes, UTF_8);
            List<String> objects = JacksonUtils.json2list(s);
            return objects;
        }
        return new ArrayList<>();
    }

    public void saveSims(List<String> sims) throws JsonProcessingException {
        db.put(Suffix.SIMS.getBytes(),JacksonUtils.toJson(sims).getBytes(UTF_8));
    }

    public List<SimulationField> getFields(String simulatorId) throws Exception {
        byte[] bytes = db.get((Suffix.FIELD + simulatorId).getBytes(UTF_8));
        if (bytes != null) {
            String s = new String(bytes, UTF_8);
            TypeReference<List<SimulationField>> valueTypeRef = new TypeReference<List<SimulationField>>() {
                @Override
                public Type getType() {
                    return super.getType();
                }
            };
           return JacksonUtils.json2pojo(s, valueTypeRef);
        }
        return new ArrayList<SimulationField>();
    }

    public Simulator getSimula(String sim) {
        byte[] bytes = this.db.get((Suffix.SIMULA + sim).getBytes());
        if (bytes != null) {
            String s = new String(bytes, UTF_8);
            Simulator simulator = null;
            try {
                simulator = JacksonUtils.json2pojo(s, Simulator.class);
                return simulator;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}
